package cn.hzc.fortess.core.interceptor;

import cn.hzc.fortess.core.SessionDataHolder;
import cn.hzc.fortess.core.common.HttpContext;
import cn.hzc.fortess.core.shiro.ShiroKit;
import cn.hzc.fortess.core.shiro.ShiroUser;
import cn.hzc.fortess.system.entity.BaseModel;
import org.apache.shiro.authc.AuthenticationException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Enumeration;

public class AttributeSetInteceptor extends HandlerInterceptorAdapter {


    private static final Logger log = LoggerFactory.getLogger(AttributeSetInteceptor.class);

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

        if (modelAndView == null || modelAndView.getViewName() == null) {
            return;
        }

        if (!modelAndView.getViewName().endsWith("html")) {
            return;
        }

        ShiroUser user = ShiroKit.getUser();

        if (user == null) {
            throw new AuthenticationException("登录失败,请重新登录！");
        } else {
            modelAndView.addObject("name", user.getName());


            if (!modelAndView.getViewName().endsWith("/form.html")) {
                return;
            }

            Enumeration<String> attrNames = HttpContext.getRequest().getAttributeNames();
            while (attrNames.hasMoreElements()) {
                String attrName = attrNames.nextElement();
                Object object = HttpContext.getRequest().getAttribute(attrName);
                if ((object instanceof BaseModel) && ((BaseModel) object).getCreateTime() != null) {
                    log.debug("open edit form - {},thread id:{}", modelAndView.getViewName(), Thread.currentThread().getId());
                    //临时保存编辑前的数据
                    SessionDataHolder.me().set(object);
                    break;
                }
            }


        }
    }
}
